package com.gxa.realm;
import com.gxa.entity.SysRole;
import com.gxa.entity.SysUser;
import com.gxa.mapper.SysRoleMapper;
import com.gxa.mapper.SysUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author MacieSerenity
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysRole roleByUserId = null;
        //创建认证信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取登录账户
        String username = String.valueOf(principalCollection.getPrimaryPrincipal());
        //数据库中的用户信息
        SysUser userByUsername = sysUserMapper.getUserByUsername(username);
        roleByUserId = sysRoleMapper.getRoleByUserId(userByUsername.getId());
        if (roleByUserId != null) {
            Set<String> role = new HashSet<>();
            role.add(roleByUserId.getRoleName());
            info.setRoles(role);
        }
        return info;
    }

    /**
     * 认证<br>
     * 将客户端传递过来的信息与数据库的信息进行对比
     *
     * @param authenticationToken 验证的Token信息
     * @return 认证信息
     * @throws AuthenticationException 认证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取客户端的用户名
        String username = String.valueOf(authenticationToken.getPrincipal());
        //根据用户名查询用户信息
        SysUser userByUsername = sysUserMapper.getUserByUsername(username);
        SimpleAuthenticationInfo info = null;
        if (userByUsername != null) {
            info = new SimpleAuthenticationInfo(userByUsername.getUsername(), userByUsername.getPassword(), "myRealm");
            info.setCredentialsSalt(ByteSource.Util.bytes(userByUsername.getSalt()));
        }
        return info;
    }
}
